//
//  SEGUhomeNetworkDoorManager.m
//  ExcellentHome
//
//  Created by 揭婧雯 on 2017/7/10.
//  Copyright © 2017年 陈区. All rights reserved.
//

#import "SEGUhomeNetworkDoorManager.h"
#import "SEGNewDoorManager.h"

//网络门开门接口
#define kOpenNetworkDoor [SEGServerManager serverUrlJoint:kClientRootURL,@"/",kUhomecp_app,@"/v1/userapp/opendoor/submit.json",nil]

@interface SEGUhomeNetworkDoorManager()
@end

@implementation SEGUhomeNetworkDoorManager

//开门
- (void)openDoor {
    // app版本
    NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
    NSString *app_Version = [infoDictionary objectForKey:@"CFBundleShortVersionString"];
    NSDictionary* netWorkOpenDoorParams = @{
                           @"userId" : kAccountUserID,
                           @"custId" : ValueToString([SEGProfileManager sharedManager].profile.custId),
                           @"doorId" : self.doorModel.doorId,
                           @"communityId" : kAccountCommunityID,
                           @"doorIdStr": self.doorModel.doorIdStr,
                           @"appVersion" : app_Version,
                           @"appType" : @"2" //APP类型：1 android 2 IOS
                           };
    @weakify(self);
    [SEGHTTPBusinessManager seg_requestJSONWithMethod:POST URLString:kOpenNetworkDoor parameters:netWorkOpenDoorParams completed:^(BOOL isSuccessed, id result, NSString *codeType, NSError *error) {
        @strongify(self);
        if (isSuccessed) {
            if (self.delegateSubject) {
                [self.delegateSubject sendNext:nil];
                [self.delegateSubject sendCompleted];
            }
        } else {
            //判断是客户端网络问题还是服务器问题
            SEGOpenNetworkDoorErroType errorType = SEGOpenNetworkDoorErroType_ServiceError;
            if (error.code == NSURLErrorTimedOut || error.code == NSURLErrorNetworkConnectionLost || error.code == NSURLErrorNotConnectedToInternet) {//客户端问题
                errorType = SEGOpenNetworkDoorErroType_APPNetworkError;
            } else if (codeType.integerValue == -1) {
                NSString *data = ValueToString([result objectForKey:@"data"]);
                if ([data isEqualToString:@"-301"] ||  [data isEqualToString:@"-302"]) {//门禁设备问题
                    errorType = SEGOpenNetworkDoorErroType_HardWareError;
                }
            }
            [self seg_dealWithOpenNetworkDoorError:errorType];
        }
    }];
}


/// 5.2.0 新增打开新网络门逻辑，使用接口同卷闸门
- (void)openNewNetworkDoor {
    NSString *urlString = [SEGServerManager serverUrlJoint:kClientRootURL,@"/door-restapi/v1/userapp/opendoor/submit.json",nil];
    NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
    NSString *app_Version = [infoDictionary objectForKey:@"CFBundleShortVersionString"];
    NSDictionary *param = @{
        @"userId": kAccountUserID?:@"",
        @"custId": kAccountCustId?:@"",
        @"doorId": self.doorModel.doorId ?:@"",
        @"communityId": kAccountCommunityID ?: @"",
        @"doorIdStr": self.doorModel.doorIdStr,
        @"appVersion": app_Version ?: @"",
        @"appType": @"2"
    };
    
    [SEGHTTPBusinessManager seg_requestJSONWithMethod:POST URLString:urlString parameters:param completed:^(BOOL isSuccessed, id result, NSString *codeType, NSError *error) {
        // 请求成功 通知代理响应状态
        if (isSuccessed) {
            if (self.delegateSubject) {
                [self.delegateSubject sendNext:nil];
                [self.delegateSubject sendCompleted];
            }
            return;
        }
        
        // 请求失败，判断是客户端网络问题还是服务器问题
        SEGOpenNetworkDoorErroType errorType = SEGOpenNetworkDoorErroType_ServiceError;
        if (error.code == NSURLErrorTimedOut || error.code == NSURLErrorNetworkConnectionLost || error.code == NSURLErrorNotConnectedToInternet) {//客户端问题
            errorType = SEGOpenNetworkDoorErroType_APPNetworkError;
        }
        [self seg_dealWithOpenNetworkDoorError:errorType];
    }];
}

- (void)seg_dealWithOpenNetworkDoorSuccess {
    //开门成功 清除错误数据
    NSString *key1 = [NSString stringWithFormat:@"DoorError%@_%ld",kAccountUserID, (unsigned long)SEGOpenNetworkDoorErroType_APPNetworkError];
    NSString *key2 = [NSString stringWithFormat:@"DoorError%@_%ld",kAccountUserID, (unsigned long)SEGOpenNetworkDoorErroType_ServiceError];
    NSString *key3 = [NSString stringWithFormat:@"DoorError%@_%ld",kAccountUserID, (unsigned long)SEGOpenNetworkDoorErroType_HardWareError];
    [[NSUserDefaults standardUserDefaults] setValue:nil forKey:key1];
    [[NSUserDefaults standardUserDefaults] setValue:nil forKey:key2];
    [[NSUserDefaults standardUserDefaults] setValue:nil forKey:key3];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

/// 处理网络门开门失败
/// @param errorType errorType
- (void)seg_dealWithOpenNetworkDoorError:(SEGOpenNetworkDoorErroType)errorType {
    NSString *key = [NSString stringWithFormat:@"DoorError%@_%ld",kAccountUserID, (unsigned long)errorType];
    NSDictionary *temp = [[NSUserDefaults standardUserDefaults] dictionaryForKey:key];
    NSMutableDictionary *errorInfoDict;
    NSInteger currentErrorCount;//当前错误次数
    NSString *currentTime = [SEGUtils stringDateByFormatString:kTimeFormatStringSec withDate:[NSDate date]];
    if (temp && temp.count > 0) {
        errorInfoDict = [NSMutableDictionary dictionaryWithDictionary:temp];
        NSString *doorId = [errorInfoDict objectForKey:@"doorId"];
        if ([doorId isEqualToString:self.doorModel.doorId]) {
            NSString *timeString = [errorInfoDict objectForKey:@"time"];
            NSDate *lastErrorTime = [SEGUtils dateFromString:timeString withFormatString:kTimeFormatStringSec];
            NSTimeInterval interval = [[NSDate date] timeIntervalSinceDate:lastErrorTime];
            if (interval >= 3600) {//时间间隔判断 超过一小时重新计算
                [errorInfoDict setObject:currentTime forKey:@"time"];
                currentErrorCount = 1;
            }else {
                NSInteger errorCount = [[errorInfoDict objectForKey:@"count"] integerValue];
                currentErrorCount = errorCount + 1;
            }
        }else {//本地不存在数据，直接保存当前门信息和当前时间
            [errorInfoDict setObject:self.doorModel.doorId forKey:@"doorId"];
            [errorInfoDict setObject:currentTime forKey:@"time"];
            currentErrorCount = 1;
        }
    }else {//本地不存在数据，直接保存当前门信息和当前时间
        errorInfoDict = [NSMutableDictionary dictionary];
        [errorInfoDict setObject:self.doorModel.doorId forKey:@"doorId"];
        [errorInfoDict setObject:currentTime forKey:@"time"];
        currentErrorCount = 1;
    }
    [errorInfoDict setObject:[NSString stringWithFormat:@"%ld",(long)currentErrorCount] forKey:@"count"];
    //保存错误次数
    [[NSUserDefaults standardUserDefaults] setValue:errorInfoDict forKey:key];
    [[NSUserDefaults standardUserDefaults] synchronize];
    
    //是否超过三次
    BOOL moreThanThreeTimes = (currentErrorCount > 3) ? YES : NO;
    NSString *titleMessage = @"";
    NSString *errorMessage = @"";
    if (moreThanThreeTimes) {
        switch (errorType) {
            case SEGOpenNetworkDoorErroType_APPNetworkError://客户端网络不稳定
            {
                errorMessage = @"当前网络不稳定";
                break;
            }
            case SEGOpenNetworkDoorErroType_ServiceError://服务器内部异常
            {
                titleMessage = @"很抱歉，手机开门出现问题，建议您：";
                errorMessage = @"使用门禁卡、密码开门，或呼叫管理处开门。";
                break;
            }
            case SEGOpenNetworkDoorErroType_HardWareError://硬件问题(门禁损坏或流量卡用完)
            {
                titleMessage = @"手机开门出现问题，建议您：";
                errorMessage = @"1、使用门禁卡、密码开门，或呼叫管理处开门；\n2、致电联系管理处反馈，方便您下次使用。";
                break;
            }
            default:
                break;
        }
        
        //开门失败一键报单接口，开门失败三次触发一键报表接口，主要是普通4G门的,蓝牙的不做
        [[SEGNewDoorManager new] requestSubmitWorkOrderWithDoorId:self.doorModel.doorId doorIdStr:self.doorModel.doorIdStr finished:^(BOOL isSuccessed, NSString *codeType, NSString *errorMessage) {
        }];
    } else {
        errorMessage = @"手机开门出错了，\n请再次点击开门试试。";
    }
    
    if (self.delegateSubject) {
        NSError *error = [NSError errorWithDomain:NSNetServicesErrorDomain code:SEGOpenDoorErrorType_NetworkDoorFail userInfo:@{NSLocalizedDescriptionKey:errorMessage, SEGOpenDoorErrorTipTitleKey:titleMessage}];
        [self.delegateSubject sendError:error];
    }
}



@end
